package com.example.flowerpcback.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.example.flowerpcback.resp.FileResp;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

public class Uploadaliyun {
    static String bucketName = "yunlianweilai";
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    static String endpoint = "oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    static String accessKeyId = "LTAI5tCWWyqcgAVwinDG71Bi";
    static String accessKeySecret = "K2BlFGzn4dG6H0d62a4cgYtMECTxf1";

    public static FileResp upFile(MultipartFile files, String path) throws Exception {
        String url;
        String img = files.getOriginalFilename();//获取图片名字
        int i = img.lastIndexOf(".");
        String suffix = img.substring(i);//后缀
        //随机生成器使名字不会重复
        String uuid = UUID.randomUUID().toString();
        String filename = path+"/"+ uuid + suffix;

        /**
         * 上传操作
         */
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = filename;

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        PutObjectResult PutObjectResult =  ossClient.putObject(bucketName, objectName,files.getInputStream());
        url="https://"+bucketName+"."+endpoint+"/"+filename;
// 关闭OSSClient。
        ossClient.shutdown();

        FileResp fileResp = new FileResp();
        fileResp.setFileUrl(url);
        fileResp.setFileName(filename);

        return fileResp;

    }

    public static String deleteFile(String fileName) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, fileName);
            return "1";
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return "0";
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return "0";
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static InputStream downloadFile(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        return ossObject.getObjectContent();
    }
}
